import java.util.*;

public class BinaryTree {

    static class TreeNode{

        private int val;
        private TreeNode left;
        private TreeNode right;

        public TreeNode(int val){
            this.val = val;
        }

    }

    private TreeNode root;

    public TreeNode createBinaryTree(){
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);
        TreeNode node6 = new TreeNode(6);
        TreeNode node7 = new TreeNode(7);
        TreeNode node8 = new TreeNode(8);
        node1.left = node2;
        node1.right = node3;
        node2.left = node4;
        node2.right = node5;
        node3.left = node6;
        node3.right = node7;
        node4.left = node8;

        return node1;
    }

    // 前序遍历
    public void preOrder(TreeNode root){
        if(root == null){
            return;
        }
        System.out.print(root.val+"  ");
        preOrder(root.left);
        preOrder(root.right);
    }
    // 中序遍历
    public void inOrder(TreeNode root){
        if (root == null){
            return;
        }
        inOrder(root.left);
        System.out.print(root.val+"  ");
        inOrder(root.right);
    }

    // 后序遍历
    public void postOrder(TreeNode root){
        if(root == null){
            return;
        }
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val+"  ");
    }

    /**
     * 获取树中节点的个数：遍历思路
     */
    public static int nodeSize;

    void size(TreeNode root) {
        if(root == null){
            return;
        }
            nodeSize++;
        size(root.left);
        size(root.right);
    }


    // 获取树中节点的个数
    public int size2(TreeNode root){
        if(root == null){
            return 0;
        }
        int left = size2(root.left);
        int right = size2(root.right);
        return left + right + 1;
    }

    /*
    获取叶子节点的个数：遍历思路
     */
    public static int leafSize = 0;

    public void getLeafTreeNodeCount1(TreeNode root){
        if(root == null){
            return;
        }
        if(root.left == null && root.right == null){
            leafSize++;
        }
        getLeafTreeNodeCount1(root.left);
        getLeafTreeNodeCount1(root.right);
    }

    public int getLeafTreeNodeCount2(TreeNode root){
        if(root == null){
            return 0;
        }
        if(root.left == null && root.right == null){
            return 1;
        }
        int left = getLeafTreeNodeCount2(root.left);
        int right = getLeafTreeNodeCount2(root.right);

        return left + right;
    }

    // 子问题思路-求叶子结点个数
    // 获取第K层节点的个数
    public int getKLevelTreeNodeCount(TreeNode root,int k){
        if(root == null){
            return 0;
        }
        if(k == 1){
            return 1;
        }
        int left = getKLevelTreeNodeCount(root.left, k - 1);
        int right = getKLevelTreeNodeCount(root.right, k - 1);

        return left + right;
    }

    // 检测值为value的元素是否存在
    public TreeNode find(TreeNode root, int val){
        if(root == null){
            return null;
        }
        if(root.val == val){
            return root;
        }
        TreeNode left = find(root.left,val);
        TreeNode right = find(root.right,val);
        if(left != null){
            return left;
        }else {
            return right;
        }
    }

    //层序遍历
    public void levelOrder(TreeNode root){
        if(root == null){
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            TreeNode cur = queue.poll();
            System.out.print(cur.val+" ");
            if(cur.left != null){
                queue.offer(cur.left);
            }
            if(cur.right != null){
                queue.offer(cur.right);
            }
        }
    }

    // 判断一棵树是不是完全二叉树
    public boolean isCompleteTree(TreeNode root){
        if(root == null){
            return true;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            TreeNode cur = queue.poll();
            if(cur == null){
                break;
            }
            queue.offer(cur.left);
            queue.offer(cur.right);
        }
        while(!queue.isEmpty()){
            if(queue.poll() != null){
                return false;
            }
        }
        return true;
    }

    // 获取二叉树的高度
    public int getHeight(TreeNode root){
        if(root == null){
            return 0;
        }
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);

        return leftHeight > rightHeight ? leftHeight+1 : rightHeight+1;
    }

    //判断一棵树是否为对称二叉树
    public boolean isSymmetric(TreeNode root) {
        if(root == null){
            return true;
        }
        return isSymmetricChild(root.left, root.right);
    }

    public boolean isSymmetricChild(TreeNode p, TreeNode q){
        if(p == null && q == null){
            return true;
        }
        if(p == null && q != null){
            return false;
        }
        if(p != null && q == null){
            return false;
        }
        if(p.val != q.val){
            return false;
        }
        return isSymmetricChild(p.left, q.right) && isSymmetricChild(p.right,q.left);
    }

    //创建一棵二叉树
    public static int i = 0;
    public static TreeNode createTree(String str){
        TreeNode root = null;
        if(str.charAt(i) != '#'){
            root  =  new TreeNode(str.charAt(i++));
            root.left = createTree(str);
            root.right = createTree(str);
        }else{
            i++;
        }
        return root;
    }

    public List<List<TreeNode>> leverOrder(TreeNode root){
        List<List<TreeNode>> ret = new ArrayList<>();
        if(root == null){
            return null;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        List<TreeNode> tmp = new ArrayList<>();
        tmp.add(root);
        ret.add(tmp);
        while(!queue.isEmpty()){
            tmp.clear();
            int size = queue.size();
            while(size-- > 0){
                TreeNode cur = queue.poll();
                tmp.add(cur);
                System.out.print(cur.val+" ");
                if(cur.left != null){
                    queue.offer(cur.left);
                }
                if(cur.right != null){
                    queue.offer(cur.right);
                }
            }
            ret.add(tmp);
        }
        return ret;
    }

    /**
     * 两棵树的最近公共祖先
     * @param root
     * @param p
     * @param q
     * @return
     */
    public TreeNode lowestCommonAncestor1(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null){
            return null;
        }
        if(p == root || q == root){
            return root;
        }
        TreeNode leftTree = lowestCommonAncestor1(root.left, p, q);
        TreeNode rightTree = lowestCommonAncestor1(root.right, p, q);
        if(leftTree != null && rightTree != null){
            return root;
        }else if(leftTree != null){
            return leftTree;
        }else{
            return rightTree;
        }
    }


    private boolean getPath(TreeNode root, TreeNode node, Stack<TreeNode> stack){
        if(root == null || node == null){
            return false;
        }
        stack.push(root);
        if(root == node){
            return true;
        }
        if(getPath(root.left, node, stack)){
            return true;
        }
        if(getPath(root.right, node, stack)){
            return true;
        }
        stack.pop();
        return false;
    }

    //最近公共祖先非递归实现
    public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null){
            return null;
        }

        //对栈的操作
        Stack<TreeNode> stackP = new Stack<>();
        Stack<TreeNode> stackQ = new Stack<>();
        getPath(root, p, stackP);
        getPath(root, q, stackQ);

        //从两个栈当中的最大栈中弹出差值元素
        int size1 = stackP.size();
        int size2 = stackQ.size();
        if(size1 > size2){
            int size = size1 - size2;
            while(size != 0){
                stackP.pop();
                size--;
            }
        }else{
            int size = size2 - size1;
            while(size != 0){
                stackQ.pop();
                size--;
            }
        }

        //现在两个栈的元素个数相同
        while(!stackP.isEmpty() && !stackQ.isEmpty()){
            if(stackP.peek() == stackQ.peek()){
                return stackP.peek();
            }
            stackP.pop();
            stackQ.pop();
        }
        return null;
    }

    /**
     * 从中序遍历和后序遍历序列构造二叉树
     */
    //定义一个变量作为递归的起始下标
//    private int postIndex = 0;
//
//    public TreeNode buildTree(int[] inorder, int[] postorder) {
//
//        //因为这里是后序遍历，所有根在最后一个下标的位置
//        postIndex = postorder.length - 1;
//        //调用另外一个创建树的方法
//        return buildChildTree(inorder, 0, inorder.length - 1, postorder);
//
//    }
//
//    //创建子树的方法（因为根已经知道，所有这里可以直接创建根
//    private TreeNode buildChildTree(int[] inorder, int inBegin, int inEnd, int[] postorder) {
//
//        //当开始下标比结束下标大时，说明便利结束了
//        if(inBegin > inEnd){
//            return null;
//        }
//        //创建根节点
//        TreeNode root = new TreeNode(postorder[postIndex]);
//        //在中序遍历中找到对应根节点的下标
//        int rootIndex = findIndex(inorder, inBegin, inEnd, postorder[postIndex]);
//
//        //找不到返回空
//        if(rootIndex == -1){
//            return null;
//        }
//        postIndex--;
//        //递归创建左子树和右子树
//        root.right = buildChildTree(inorder, rootIndex + 1, inEnd, postorder);
//        root.left = buildChildTree(inorder, inBegin, rootIndex - 1, postorder);
//
//        return root;
//    }
//
//    //找下标的方法
//    private int findIndex(int[] inorder, int inBegin, int inEnd, int key){
//        for(int i = inBegin; i <= inEnd; i++){
//            if(inorder[i] == key){
//                return i;
//            }
//        }
//        return -1;
//    }

    /**
     * 从前序和中序遍历序列构造二叉树
     */
    //定义一个成员变量作为每次递归的起始下标
    //因为局部变量的作用域是函数，出了函数就消失了
    //但是我们期待的是每次递归都从上一次进入递归前的下标开始，而不是进入递归后的局部变量priIndex
//    public int priIndex;
//
//    public TreeNode buildTree(int[] preorder, int[] inorder) {
//
//        //调用子递归创建二叉树
//        return buildChildTree(preorder, inorder, 0, inorder.length - 1);
//
//    }
//
//    private TreeNode buildChildTree(int[] preorder, int[] inorder, int inBegin, int inEnd) {
//
//        //当在中序遍历中的开始下标大于结束下标时，此时说明递归结束返回即可
//        if(inBegin > inEnd){
//            return null;
//        }
//
//        //先创建根节点
//        TreeNode root = new TreeNode(preorder[priIndex]);
//
//        //在中序遍历序列中找到前序遍历中的根节点的下标
//        int rootIndex = findIndex(inorder, inBegin, inEnd, preorder[priIndex]);
//
//        //找不到返回空即可
//        if(rootIndex == -1){
//            return null;
//        }
//
//        //找到之后往后走
//        priIndex++;
//        //递归创建左子树和右子树
//        root.left = buildChildTree(preorder, inorder, inBegin, rootIndex - 1);
//        root.right = buildChildTree(preorder, inorder, rootIndex + 1, inEnd);
//
//        return root;
//    }
//
//    //在中序遍历中找前序遍历中的根节点的下标
//    private int findIndex(int[] inorder, int inBegin, int inEnd, int key){
//        for(int i = inBegin; i <= inEnd; i++){
//            if(inorder[i] == key){
//                return i;
//            }
//        }
//        return -1;
//    }

    /**
     * 通过二叉树创建字符串
     * @param root
     * @return
     */
    public String tree2str(TreeNode root) {

        //定义一个StringBuilder来返回最后的字符串
        StringBuilder stringBuilder = new StringBuilder();
        //调用子方法
        tree2strChild(root, stringBuilder);
        return stringBuilder.toString();
    }

    //因为需要返回字符串所有又定义了一个有两个参数方法，用来递归
    private void tree2strChild(TreeNode t, StringBuilder stringBuilder){

        //如果t为空，直接返回即可
        if(t == null){
            return;
        }
        //不为空，把t节点的值加入到stringBuilder中
        stringBuilder.append(t.val);
        //t的左子树不为空
        if(t.left != null){
            //需要加入一个(
            stringBuilder.append("(");
            //递归左子树
            tree2strChild(t.left, stringBuilder);
            //递归结束后，加入一个)
            stringBuilder.append(")");
        }else{
            //左子树为空，右子树也为空
            if(t.right == null){
                //直接返回
                return;
            }else{
                //右子树不为空，需要加入()
                stringBuilder.append("()");
            }
        }
        //右子树不为空
        if(t.right != null){
            //加入(
            stringBuilder.append("(");
            //递归右子树
            tree2strChild(t.right, stringBuilder);
            //递归结束加入)
            stringBuilder.append(")");
        }else{
            //右子树为空,返回
            return;
        }
    }

    public void preOrderNor(TreeNode root) {
        if (root == null) {
            return;
        }
        TreeNode cur = root;
        TreeNode top = null;
        Stack<TreeNode> stack = new Stack<>();
        while (cur != null || !stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                System.out.print(cur.val + " ");
                cur = cur.left;
            }
            top = stack.pop();
            cur = top.right;
        }
    }

    public void inOrderNor(TreeNode root){
        if(root == null){
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode top = null;
        while(cur != null || !stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            top = stack.pop();
            System.out.print(top.val + " ");
            cur = top.right;
        }
    }

    public void postOrderNor(TreeNode root){
        if(root == null){
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode top = null;
        TreeNode prev = null;
        while(cur != null || !stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            top = stack.peek();
            if (top.right == null || top.right == prev) {
                stack.pop();
                System.out.print(top.val + " ");
                prev = top;
            } else {
                cur = top.right;
            }
        }
    }

    //翻转二叉树
    public TreeNode invertTree(TreeNode root) {
        if(root == null){
            return null;
        }
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

    //相同的树
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p == null && q == null){
            return true;
        }
        if(p == null && q != null || p != null && q == null){
            return false;
        }
        if(p.val != q.val){
            return false;
        }
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }

    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if(root == null){
            return false;
        }
        if(isSameTree1(root, subRoot)){
            return true;
        }
        if(isSubtree(root.left, subRoot)){
            return true;
        }
        if(isSubtree(root.right, subRoot)){
            return true;
        }
        return false;
    }

    public boolean isSameTree1(TreeNode p, TreeNode q){
        if(p == null && q == null){
            return true;
        }
        if(p == null && q != null){
            return false;
        }
        if(p != null && q == null){
            return false;
        }
        if(p.val != q.val){
            return false;
        }
        return isSameTree1(p.left, q.left) && isSameTree1(p.right, q.right);
    }

    public boolean isBalanced(TreeNode root) {
        if(root == null){
            return true;
        }
        int leftHeight = Height(root.left);
        int rightHeight = Height(root.right);

        return Math.abs(leftHeight - rightHeight) <= 1 && isBalanced(root.left) && isBalanced(root.right);
    }

    //平衡二叉树
    public int Height(TreeNode root){
        if(root == null){
            return 0;
        }
        int leftHeight = Height(root.left);
        int rightHeight = Height(root.right);
        return (leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1);
    }
    
}
